$(async function () {
  var phone = getCookie("lgc");
  // if (!phone) {
  //   location.href = "./login.html?returnUrl=" + encodeURIComponent(location.href);
  // }

  $(".cart-to-login").css(phone ? { 'display': 'none' } : { 'display': 'block' })
  $(".goToLogin").click(function () {
    $(location).attr("href", "../html/login.html");
  })
  $(".goToRegister").click(function () {
    $(location).attr("href", "../html/register.html");
  })

  var result = await searchShoppingCarByUser({ phone });  //await 异步改同步
  console.log(result);
  var { status, list } = result;

  if (status) {

    var html = ""
    var sum = ""
    list.forEach(({ id, title, price, bigimg, goodsprice, byNum, subtotal, isChecked }) => {

      html += ` <tr data-id="${id}" class="goods-item">
      <td class="td-check">
        <label class="checkbox-label checkbox-one">
          <input class=" check-one"  type="checkbox">
          <!-- <i class="i"></i> -->
        </label>
      </td>
      <td class="td-img">
        <img src="${bigimg}" alt="">
      </td>
      <td class="td-infos">
        <div class="td-infos-top clearfix">
          <div class="fl">
            <h5>${title}</h5>
            <p><span>颜色:乌卡拉银;尺寸:XL</span></p>
          </div>
          <div class="fr">
            <p><span class="rmbOne"></span><span class="infos-price">${price}</span></p>
            <p><span class="rmbTwo"></span><span class="infos-mktprice">${goodsprice}</span></p>
          </div>
        </div>
        <div class="td-infos-bot clearfix">
          <p class="fl">
            <span>数量：</span>
            <span class="reduce">-</span>
            <input type="text" class="num-input" value="${byNum}" />
            <span class="add">+</span>
          </p>
          <p class="fr">
            <span class="delete-one">删除</span>
          </p>
        </div>
      </td>
    </tr>`

      var sum = `<i class="total-num">共 ${byNum} 件</i>`;
    })

    $(".cart-table").html(html);
    // $(".total-num").html(sum)
  }

  // 全选
  $(".checkbox-input").click(function () {
    var status = $(this).prop("checked");
    console.log(status);
    $(".check-one").prop("checked", status);
    $(".checkbox-input").prop("checked", status);
    getTotal();
  })

  //单选
  $(".check-one").click(function () {
    // console.log(this);
    isAllchecked();
    getTotal();
  })

  //加法
  $(".add").click(async function () {
    var id = $(this).parents("tr").attr("data-id");
    console.log(id);
    var result = await addGoods({ id });
    var { status, msg } = result;
    if (!status) throw msg;


    var num = $(this).prev().val() * 1;
    // console.log(num);
    num++;
    $(this).prev().val(num);
    getTotal();
  })

  //减法
  $(".reduce").click(async function () {


    var num = $(this).next().val() * 1;
    console.log(num);
    if (num == 1) {
      return false;
    }
    num--;
    if (num == 1) {
      $(this).text("");
    }
    $(this).next().val(num);
    getTotal();
    var id = $(this).parents("tr").attr("data-id");
    console.log("-", id);
    var result = await reduceGoods({ id });
    var { status, msg } = result;
    if (!status) throw msg;
  })

  //单删
  $(".delete-one").click(async function () {

    $(this).parents("tr").remove();
    if (confirm("是否删除该商品?")) {
      var gid = $(this).parents("tr").attr("data-id");
      console.log(gid);
      var result = await delGoods({ ids: gid });
      var { status, msg } = result;
      if (!status) throw msg;

      $(this).parents("tr").remove();
      isAllchecked();
      getTotal();
    }
  })

  //全删
  $(".delete-multi").click(async function () {
    if ($(".check-one:checked")) {

      var len = $(".check-one:checked").length;
      console.log(len);
      if (len > 0) {
        if (confirm("是否删除选中的商品")) {
          var list = $(".check-one:checked").parents("tr").map(function () {
            return $(this).attr("data-id")
          }).get();
          console.log(list);

          var result = await delGoods({ ids: list.join(",") });
          var { status, msg } = result;
          if (!status) throw msg;

          $(".check-one:checked").parents("tr").remove();
          isAllchecked();
          getTotal();
        }

      } else {
        alert("请至少选中一件商品!")
      }
    }
  })

  //结算
  function getTotal () {
    var allPrice = 0;
    var sum = 0;
    $(".check-one:checked").each(function () {
      var num = $(this).parents("td").nextAll(".td-infos").find(".num-input").val() * 1;
      // console.log(num);

      var subTotal = $(this).parents("td").nextAll(".td-infos").find(".infos-price").text().replace(/￥/g, "") * 1;
      console.log(subTotal);
      sum += num;
      allPrice += num * subTotal;
    })
    $(".total-num").text(`共${sum}件`);
    $(".price").text(`￥${allPrice.toFixed(2)}`);
  }



})

function isAllchecked () {
  if ($(".check-one").length && $(".check-one:checked").length == $(".check-one").length) {
    $(".checkbox-input").prop("checked", true)
  } else {
    $(".checkbox-input").prop("checked", false)

  }
}